package com.brilliance.project.common.report;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRXlsAbstractExporter;
import net.sf.jasperreports.engine.export.JRXlsAbstractExporterParameter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.brilliance.project.common.exception.BaseJasperReportException;
import com.brilliance.project.common.exception.ErrorReferenceReport;

public class XlsxReportExportImpl implements IBaseReportExport {
	private static Log log = LogFactory.getLog(XlsxReportExportImpl.class);

	public String jasperreportFilePath = null;

	public void setJasperreportFilePath(String jasperreportFilePath) {
		this.jasperreportFilePath = jasperreportFilePath;
	}

	public void export(HttpServletRequest request,
			HttpServletResponse response, JasperPrint jasperPrint,
			String fileName) {
		// TODO Auto-generated method stub
		OutputStream outputStream = null;

		try {
			outputStream = response.getOutputStream();
		} catch (IOException ioe) {
			ioe.printStackTrace();
			log.error(ioe.toString());
			// 从Response中取得OutputStream时发生错误
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_OUTPUTSTREAM_ERROR);
		} /* end of try ... catch */

		try {
			// response.setContentType(ReportConstant.CONTENT_TYPE_HTML);
			response.setContentType(ReportConstant.CONTENT_TYPE_EXCEL);
			response.setCharacterEncoding(ReportConstant.CHARACTER_ENCODING_UTF_8);

			if (fileName != null && !fileName.equals("")) {
				response.setHeader(ReportConstant.HEADER_CONTENT,
						ReportConstant.HEADER_INLINE + fileName);
			} /* end of if */

			// 使用JRPdfExproter导出excel报表
			JRXlsxExporter exporter = new JRXlsxExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
					outputStream);
			exporter.exportReport();
		} catch (Exception ex) {
			log.error(ex.toString());
			ex.printStackTrace();
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_PRINTWRITER_ERROR);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException ex) {
					log.error(ex.toString());
					ex.printStackTrace();
				}
			} /* end of if */
		} /* end of try ... catch ... finally */

	}

	public void view(HttpServletRequest request, HttpServletResponse response,
			Map params, JRDataSource dataSource, String fileName) {
		// TODO Auto-generated method stub
		OutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
		} catch (IOException ioe) {
			ioe.printStackTrace();
			log.error(ioe.toString());
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Exception ex) {
					log.error(ex.toString());
					ex.printStackTrace();
				}
			} /* end of if */
			// 从Response中取得OutputStream时发生错误
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_OUTPUTSTREAM_ERROR);
		} /* end of try ... catch */

		try {
			JasperPrint jasperPrint = new GenerateJasperPrint(request
					.getSession().getServletContext()
					.getRealPath(jasperreportFilePath), params, dataSource)
					.getJasperPrint();
			// 将填充完的japserPrint放入session中。
			request.getSession().setAttribute(
					BaseHttpServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
					jasperPrint);
			// 取得japserPrintList
			List jasperPrintList = BaseHttpServlet.getJasperPrintList(request);

			if (jasperPrintList == null) {
				throw new BaseJasperReportException(
						"在Http Session中没有找到JasperPrint List");
			} /* end of if */

			response.setContentType(ReportConstant.CONTENT_TYPE_EXCEL);
			response.setCharacterEncoding(ReportConstant.CHARACTER_ENCODING_UTF_8);

			response.setHeader(
					ReportConstant.HEADER_CONTENT,
					ReportConstant.HEADER_ATTACHMENT
							+ URLEncoder.encode(fileName,
									ReportConstant.CHARACTER_ENCODING_UTF_8)
							+ ReportConstant.HEADER_ATTACHMENT_EXCEL);

			// Xls格式的导出器 JRXlsAbstractExport
			JRXlsAbstractExporter exporter = getXlsExporter();

			// 在导出器中放入导出的 japserPrintList
			exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST,
					jasperPrintList);

			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
					outputStream);
			// 设置报表的字符集
			exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING,
					ReportConstant.CHARACTER_ENCODING_UTF_8);// 设置报表的字符集
			// 设置Xls的属性
			exporter.setParameter(
					JRXlsAbstractExporterParameter.IS_ONE_PAGE_PER_SHEET,
					Boolean.FALSE);
			exporter.setParameter(
					JRXlsAbstractExporterParameter.IS_WHITE_PAGE_BACKGROUND,
					Boolean.FALSE);
			exporter.setParameter(
					JRXlsAbstractExporterParameter.IS_DETECT_CELL_TYPE,
					Boolean.TRUE);// 自动判断格式

			// 导出
			exporter.exportReport();
		} catch (Exception ex) {
			log.error(ex.toString());
			ex.printStackTrace();
			throw new BaseJasperReportException(
					ErrorReferenceReport.CAN_NOT_CREATE_EXCEL_REPORT);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Exception ex) {
					log.error(ex.toString());
					ex.printStackTrace();
				} /* end of try catch */
			} /* end of if */
		} /* end of try ... catch ... finally */
	}

	public void viewList(HttpServletRequest request,
			HttpServletResponse response, Map params,
			List<? extends JRDataSource> dataSourceList, String fileName) {
		// TODO Auto-generated method stub

	}

	/**
	 * 利用报表使用JExcel生成xls报表
	 * 
	 * @return
	 */
	protected JRXlsAbstractExporter getXlsExporter() {
		return new JExcelApiExporter();
	}

	@Override
	public void export(JasperPrint jasperPrint, String fileName) {
		OutputStream outputStream = null;

		try {
			outputStream = new FileOutputStream(fileName);
		} catch (FileNotFoundException e) {
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_OUTPUTSTREAM_ERROR, e);
		}

		try {
			// 使用JRPdfExproter导出excel报表
			JRXlsxExporter exporter = new JRXlsxExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
					outputStream);
			exporter.exportReport();
		} catch (Exception ex) {
			log.error(ex.toString(), ex);
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_PRINTWRITER_ERROR);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException ex) {
					log.error(ex.toString(), ex);
				}
			} /* end of if */
		} /* end of try ... catch ... finally */
	}

	@Override
	public void export(List<JasperPrint> jasperPrintList, String fileName,
			String[] sheetNames) {
		OutputStream outputStream = null;

		try {
			outputStream = new FileOutputStream(fileName);
		} catch (FileNotFoundException e) {
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_OUTPUTSTREAM_ERROR, e);
		}

		try {
			// 使用JRPdfExproter导出excel报表
			JRXlsxExporter exporter = new JRXlsxExporter();
			// exporter.setParameter(JRExporterParameter.JASPER_PRINT,
			// jasperPrint);
			exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST,
					jasperPrintList);
			exporter.setParameter(JRXlsAbstractExporterParameter.SHEET_NAMES,
					sheetNames);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
					outputStream);
			exporter.exportReport();
		} catch (Exception ex) {
			log.error(ex.toString(), ex);
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_PRINTWRITER_ERROR);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException ex) {
					log.error(ex.toString(), ex);
				}
			} /* end of if */
		} /* end of try ... catch ... finally */
	}

	@Override
	public InputStream exportForInputStream(JasperPrint jasperPrint,
			String fileName) {
		// TODO Auto-generated method stub
		return null;
	}

	// /**
	// * 利用报表使用JExcel生成xls报表
	// * @return
	// */
	// protected JRXlsAbstractExporter getXlsExporter() {
	// return new JRXlsExporter();
	// }

}
